//
//  EVEAPICoreDataController.m
//  EVE Mac Suite
//
//  Created by Vadim Lozko on 2/9/09.
//  Copyright 2009 __Vadim__. All rights reserved.
//

#import "EVEAPICoreDataController.h"
#import "EMSGeneralUtils.h"


@implementation EVEAPICoreDataController

+(EVEAPICoreDataController*)coreDataController
{
	static EVEAPICoreDataController *coreDataController;
	
	@synchronized(self)
	{
		if (!coreDataController)
			coreDataController = [[EVEAPICoreDataController alloc] init];
		
		return coreDataController;
	}
	return nil;
}

- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
	
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    return managedObjectModel;
}

- (NSPersistentStoreCoordinator *) persistentStoreCoordinator {
	
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
    NSError* error = nil;
    NSString* applicationSupportFolder = [EMSGeneralUtils applicationSupportFolder];    
    NSURL* url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent: CORE_DATA_STORE_FULL_NAME]];
	
	NSFileManager* defaultManager = [NSFileManager defaultManager];
	if([defaultManager fileExistsAtPath:[url path]])
	{
		NSDictionary* oldMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:nil URL:url error:&error];
		if(![[self managedObjectModel] isConfiguration:nil compatibleWithStoreMetadata:oldMetadata])
		{
#ifdef DEBUG
			NSLog(@"Old store incompatible. Removing.");
#endif
			[defaultManager removeItemAtPath:[url path] error:&error];
			if(error)
			{
				NSLog(@"Error removing old store: %@", [error localizedDescription]);
			}
		}
	}
	
	
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSBinaryStoreType configuration:nil URL:url options:nil error:&error]){
        [[NSApplication sharedApplication] presentError:error];
    }    
	
    return persistentStoreCoordinator;
}


- (NSManagedObjectContext *) managedObjectContext {
	
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
	
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
		[managedObjectContext setUndoManager:nil];
    }
    
    return managedObjectContext;
}

- (NSManagedObjectContext *)apiManagedObjectContext {
	if (apiManagedObjectContext != nil) {
		return apiManagedObjectContext;
	}
	
	NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
	if (coordinator != nil) {
		apiManagedObjectContext = [[NSManagedObjectContext alloc] init];
		[apiManagedObjectContext setPersistentStoreCoordinator:coordinator];
	}
	
	return apiManagedObjectContext;
}


- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window {
    return [[self managedObjectContext] undoManager];
}


- (void) saveData{
	
    NSError *error = nil;
    if (![[self managedObjectContext] save:&error]) {
        [[NSApplication sharedApplication] presentError:error];
    }
	if(error)
	{
		NSLog(@"Error Saving Core Data store: %@\nDetails: %@",[error localizedDescription], [error userInfo]);
	}
}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
	
    NSError *error;
    int reply = NSTerminateNow;
    
    if (managedObjectContext != nil) {
        if ([managedObjectContext commitEditing]) {
            if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

                BOOL errorResult = [[NSApplication sharedApplication] presentError:error];
				
                if (errorResult == YES) {
                    reply = NSTerminateCancel;
                } 
				
                else {
					
                    int alertReturn = NSRunAlertPanel(nil, @"Could not save changes while quitting. Quit anyway?" , @"Quit anyway", @"Cancel", nil);
                    if (alertReturn == NSAlertAlternateReturn) {
                        reply = NSTerminateCancel;	
                    }
                }
            }
        } 
        
        else {
            reply = NSTerminateCancel;
        }
    }
    
    return reply;
}

- (void) dealloc {
	
    [managedObjectContext release], managedObjectContext = nil;
    [persistentStoreCoordinator release], persistentStoreCoordinator = nil;
    [managedObjectModel release], managedObjectModel = nil;
    [super dealloc];
}

@end
